package org.tpdata.api.cdss.homepage;

import business.cdss.InsertSimilarRecord;
import business.cdss.MatchWeight;
import business.cdss.ShowWeightTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.yamlbeans.YamlException;
import common.Data;
import common.RunCaseJson;
import common.SetUpTearDown1;
import exceptions.TestNGRetry;
import io.qameta.allure.*;
import io.restassured.response.Response;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utils.MyMath;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;

public class GetReportDatas extends SetUpTearDown1 {

    Logger log = Logger.getLogger(GetReportDatas.class);

    //先调用/api-es/similarnew/data/getPatientList.json和/api-python/generalSimilarity/insertSimilarRecord接口
    InsertSimilarRecord insertSimilarRecord = new InsertSimilarRecord();
    HashMap hashMap;

    {
        try {
            hashMap = insertSimilarRecord.insertSimilarRecord();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (YamlException e) {
            e.printStackTrace();
        }
    }

    //再调用/api-python/generalSimilarity/showWeightTemplate接口
    ShowWeightTemplate showWeightTemplate = new ShowWeightTemplate();

    String jsonstr;

    {
        try {
            jsonstr = showWeightTemplate.showWeightTemplate();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (YamlException e) {
            e.printStackTrace();
        }
    }

    MatchWeight matchWeight = new MatchWeight();
    String inPatientNos;
    int total;

    {
        try {
            JSONObject jb = matchWeight.matchWeight(hashMap.get("patientcode"), jsonstr, hashMap.get("hospitalcode"));
            //一般totalLength的值是20
            total = jb.getIntValue("totalLength");
            JSONArray jsonArray = jb.getJSONArray("localData");
            ArrayList list = new ArrayList();
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject) object;
                String inpatient_no = jsonObject.getString("inpatient_no");
                String hospital_code = jsonObject.getString("hospital_code");
                String a = inpatient_no + "|" + hospital_code;
                list.add(a);
            }
            inPatientNos = StringUtils.join(list, ",");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (YamlException e) {
            e.printStackTrace();
        }
    }

    @Story("相似病例智能分析-获取ReportDatas")
    @Parameters({"reportNos", "uri"})
    @Test(retryAnalyzer = TestNGRetry.class, description = "判断住院基本信息-年龄，性别，病例分型，转归，吸烟史的总数是否与逾期相符")
    public void runCase(String reportNos, String uri) {

        JSONObject json = new JSONObject();
        Data data = envSetUp();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("authName", data.getUserName());
        json.put("org_ids", "true");
        json.put("reportNos", reportNos);
        json.put("inPatientNos", inPatientNos);
//        json.put("",);
        log.info(json.toString());

        Response response = RunCaseJson.runCase(json, "post", uri);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);

        JSONObject obj = JSON.parseObject(jsonStr);

        JSONArray jsonArray = obj.getJSONArray("responseData");
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            JSONArray js = jsonObject.getJSONObject("data").getJSONArray("rows");
            int sum = 0;
            for (Object ob : js) {
                JSONObject jb = (JSONObject) ob;
                int count = jb.getIntValue("count");
                sum = sum + count;
            }
            //对每个rows的总和进行判断是否等于total的值
            Assert.assertEquals(sum, total);
        }

    }


    @Parameters({"reportNos1", "uri"})
    @Test(retryAnalyzer = TestNGRetry.class, description = "判断住院基本信息-入住ICU率,患者死亡率,30天再入院率总数是否与逾期相符")
    public void runCase1(String reportNos1, String uri) {

        JSONObject json = new JSONObject();
        Data data = envSetUp();
//        Map<String,String > json=new HashMap<String, String>();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("authName", data.getUserName());
        json.put("org_ids", "true");
        json.put("reportNos", reportNos1);
        json.put("inPatientNos", inPatientNos);
//        json.put("",);
        log.info(json.toString());

        Response response = RunCaseJson.runCase(json, "post", uri);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);

        JSONObject obj = JSON.parseObject(jsonStr);

        JSONArray jsonArray = obj.getJSONArray("responseData");
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            JSONArray js = jsonObject.getJSONObject("data").getJSONArray("rows");
            if (js.size() > 0) {
                for (Object ob : js) {
                    JSONObject jb = (JSONObject) ob;
                    int count = jb.getIntValue("total");
                    //对每个rows的total值进行判断是否等于totalLength的值
                    Assert.assertEquals(count, total);
                }
            } else {
                log.info("data数据为空");
            }


        }

    }


    @Parameters({"reportNos2", "uri"})
    @Test(retryAnalyzer = TestNGRetry.class, description = "判断诊断信息-诊断+药品+检验（一般临床检验、血液学检查、临床化学检查、细胞免疫学检查、病原微生物镜检、培养与鉴定）+检查（一般检查、肺功能检查）的比例值是否与逾期相符")
    public void runCase2(String reportNos2, String uri) {

        JSONObject json = new JSONObject();
        Data data = envSetUp();
//        Map<String,String > json=new HashMap<String, String>();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("authName", data.getUserName());
        json.put("org_ids", "true");
        json.put("reportNos", reportNos2);
        json.put("inPatientNos", inPatientNos);
//        json.put("",);
        log.info(json.toString());

        Response response = RunCaseJson.runCase(json, "post", uri);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);

        JSONObject obj = JSON.parseObject(jsonStr);

        JSONArray jsonArray = obj.getJSONArray("responseData");
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            JSONArray js = jsonObject.getJSONObject("data").getJSONArray("rows");
            if (js.size() > 0) {
                for (Object ob : js) {
                    JSONObject jb = (JSONObject) ob;
                    int count = jb.getIntValue("count");
                    int value = jb.getIntValue("value");
                    //对每个rows的value值进行判断count/total的商是否相等
                    String c = MyMath.div(count, total);

                    Assert.assertEquals(c, value);
                }
            } else {
                log.info("data数据为空");
            }


        }

    }


    @Parameters({"reportNos3", "uri"})
    @Test(retryAnalyzer = TestNGRetry.class, description = "判断诊断信息-诊断+药品+检验（一般临床检验、血液学检查、临床化学检查、细胞免疫学检查、病原微生物镜检、培养与鉴定）+检查（一般检查、肺功能检查）的比例值是否与逾期相符")
    public void runCase3(String reportNos3, String uri) {

        JSONObject json = new JSONObject();
        Data data = envSetUp();
//        Map<String,String > json=new HashMap<String, String>();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("authName", data.getUserName());
        json.put("org_ids", "true");
        json.put("reportNos", reportNos3);
        json.put("inPatientNos", inPatientNos);
//        json.put("",);
        log.info(json.toString());

        Response response = RunCaseJson.runCase(json, "post", uri);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);

        JSONObject obj = JSON.parseObject(jsonStr);

        JSONArray jsonArray = obj.getJSONArray("responseData");
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            JSONArray js = jsonObject.getJSONObject("data").getJSONArray("rows");
            if (js.size() > 0) {
                for (Object ob : js) {
                    JSONObject jb = (JSONObject) ob;
                    int count = jb.getIntValue("count");
                    int value = jb.getIntValue("value");
                    //对每个rows的value值进行判断count/total的商是否相等
                    int c = MyMath.divper(count, total);

                    Assert.assertEquals(c, value);
                }
            } else {
                log.info("data数据为空");
            }


        }

    }
}
